package cc.siyecao.fastdfs.command.storage;


import cc.siyecao.fastdfs.model.FileInfo;
import cc.siyecao.fastdfs.model.RecvPackageInfo;
import cc.siyecao.fastdfs.protocol.ProtocolConstants;
import cc.siyecao.fastdfs.util.BytesUtil;
import cc.siyecao.fastdfs.util.ProtocolUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * 文件查询命令
 *
 * @author lyt
 */
public class QueryFileInfoCommand extends FdfsStorageCommand<FileInfo> {

    /**
     * 文件查询命令
     *
     * @param groupName
     * @param remoteFileName
     */
    public QueryFileInfoCommand(String groupName, String remoteFileName) {
        this.groupName = groupName;
        this.fileName = remoteFileName;

    }

    @Override
    protected void send(OutputStream out, Charset charset) throws Exception {
        byte[] header;
        byte[] groupBytes;
        byte[] fileNameBytes;
        byte[] bs;
        int groupLen;
        fileNameBytes = fileName.getBytes( charset );
        groupBytes = new byte[ProtocolConstants.FDFS_GROUP_NAME_MAX_LEN];
        bs = groupName.getBytes( charset );
        Arrays.fill( groupBytes, (byte) 0 );
        if (bs.length <= groupBytes.length) {
            groupLen = bs.length;
        } else {
            groupLen = groupBytes.length;
        }
        System.arraycopy( bs, 0, groupBytes, 0, groupLen );
        header = ProtocolUtil.packHeader( STORAGE_PROTO_CMD_QUERY_FILE_INFO, +groupBytes.length + fileNameBytes.length, (byte) 0 );
        byte[] wholePkg = new byte[header.length + groupBytes.length + fileNameBytes.length];
        System.arraycopy( header, 0, wholePkg, 0, header.length );
        System.arraycopy( groupBytes, 0, wholePkg, header.length, groupBytes.length );
        System.arraycopy( fileNameBytes, 0, wholePkg, header.length + groupBytes.length, fileNameBytes.length );
        out.write( wholePkg );
    }

    @Override
    protected FileInfo receive(InputStream in, Charset charset) throws Exception {
        RecvPackageInfo pkgInfo = ProtocolUtil.recvPackage( in, STORAGE_PROTO_CMD_RESP, 3 * ProtocolConstants.FDFS_PROTO_PKG_LEN_SIZE + ProtocolConstants.FDFS_IPADDR_SIZE );
        this.errno = pkgInfo.errno;
        if (pkgInfo.errno != 0) {
            return null;
        }
        long fileSize = BytesUtil.buff2long( pkgInfo.body, 0 );
        int createTimestamp = (int) BytesUtil.buff2long( pkgInfo.body, ProtocolConstants.FDFS_PROTO_PKG_LEN_SIZE );
        int crc32 = (int) BytesUtil.buff2long( pkgInfo.body, 2 * ProtocolConstants.FDFS_PROTO_PKG_LEN_SIZE );
        String sourceIpAddr = (new String( pkgInfo.body, 3 * ProtocolConstants.FDFS_PROTO_PKG_LEN_SIZE, ProtocolConstants.FDFS_IPADDR_SIZE )).trim();
        return new FileInfo( true, FileInfo.FILE_TYPE_NORMAL, fileSize, createTimestamp, crc32, sourceIpAddr );
    }
}
